package cn.lyjuan.android.demofive.ui.slide.load;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import cn.lyjuan.android.demofive.R;

/**
 * 上滑加载
 * Created by chad on 2016/3/27.
 */
public class SlideUpLoadListView extends ListView implements AbsListView.OnScrollListener
{
    private Context context;
    private View footer;

    private boolean isLoading = false;// 标识是否正在加载中

    public SlideUpLoadListView(Context context)
    {
        super(context);
        init(context);
    }
    public SlideUpLoadListView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context);
    }
    public SlideUpLoadListView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context)
    {
        this.context = context;
        LayoutInflater lf = LayoutInflater.from(context);
        this.footer = lf.inflate(R.layout.ui_slide_load_up_load_footer, null, false);
        footer.setVisibility(View.GONE);

        this.addFooterView(footer);
        this.setOnScrollListener(this);
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState)
    {
        int last = this.getLastVisiblePosition();
        int total = this.getCount();
        Log.w(SlideUpLoadListView.class.getSimpleName(), "onScrollStateChanged view >> " +
                view.getClass().getSimpleName() + " scrollState >> " + scrollState
                + " last >> " + last + " total >> " + total);

        if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) return;

        if (last < total - 1) return ;

        if (isLoading) return;

        Log.i(SlideUpLoadListView.class.getSimpleName(), "onScrollStateChanged start load");

        this.isLoading = true;
        footer.setVisibility(View.VISIBLE);
        loader.loadMore();
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
    {
        Log.w(SlideUpLoadListView.class.getSimpleName(), "onScroll first >> " + firstVisibleItem
                + " vis >> " + visibleItemCount + " total >> " + totalItemCount);
    }

    private SlideUpLoadActivity.LoadMore loader;

    public void setLoader(SlideUpLoadActivity.LoadMore loader)
    {
        this.loader = loader;
    }

    public void onLoadComplete()
    {
        this.isLoading = false;
        this.footer.setVisibility(View.GONE);
        Toast.makeText(this.context, "加载完成", Toast.LENGTH_SHORT).show();
    }
}
